#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
@Project ：Employment_class 
@File    ：08_MyWebFramework.py
@IDE     ：PyCharm 
@Author  ：XiaoDengYa
@Date    ：2021/7/19/019 9:25 
"""

import time

# 设置静态文件根目录
HTML_ROOT_DIR = "./html"


class Application(object):
    def __init__(self, urls):
        self.urls = urls

    def __call__(self, env, start_response):
        path = env.get("PATH_INFO", "/")
        if path.startswith("/static"):
            filename = path[7:]
            try:
                file = open(HTML_ROOT_DIR + filename, "rb", encoding="gbk")
            except IOError:
                status = "404 Not Found"
                headers = []
                start_response(status, headers)
                return "not found"
            else:
                file_data = file.read()
                file.close()
                status = "200 OK"
                headers = [("Content-Type", "application/html")]
                start_response(status, headers)
                return file_data.decode("utf-8")
        else:
            for url, handler in self.urls:
                if path == url:
                    return handler(env, start_response)
            status = "404 Not Found"
            headers = []
            start_response(status, headers)
            return "not found"


def show_ctime(env, start_response):
    status = "200 OK"
    headers = [
        ("Content-Type", "text/plain")
    ]
    start_response(status, headers)
    return time.ctime()


def say_hello(env, start_response):
    status = "200 OK"
    headers = [
        ("Content-Type", "text/plain")
    ]
    start_response(status, headers)
    return "hello itcast"


def say_haha(env, start_response):
    status = "200 OK"
    headers = [
        ("Content-Type", "text/plain")
    ]
    start_response(status, headers)
    return "hello haha"


urls = [
    ("/", show_ctime),
    ("/ctime", show_ctime),
    ("/sayhello", say_hello),
    ("/sayhaha", say_haha),
]

app = Application(urls)
